package com.ying.tests.BBBbook.java8.Chapter1;

import com.google.common.base.Stopwatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 比我强的人还在努力，我真是个垃圾，这道理都不懂吗！
 * url: https://github.com/java8
 * 第一章：为什么要关心Java
 */
public class Chapter1 {

    private static final Logger logger = LoggerFactory.getLogger(Chapter1.class);

    public static void main(String[] args) {
//        test1();      //按照重量排序
//        test2();      //内部类与方法引用
//        test3();
//        test4();
//        test3_1(Apple::test3_method);                         // 传递方法
//        test4_1(Apple::test4_method);
//        test3_1((Apple a) -> "green".equals(a.getColor()));   // 从传递方法到lambda
//        test4_1((Apple a) -> a.getWeight() > 150);
//        test4_1((Apple a) -> "green".equals(a.getColor()) || a.getWeight() >150);
//        test5();      //传统过滤并分组
//        test5_1();    //使用lambd过滤并分组
        test6();
    }

    /**
     * 按照重量排序
     */
    private static void test1() {
        List<Apple> list = new ArrayList<Apple>();
        list.add(new Apple("臭狗砸", 222, "red"));
        list.add(new Apple("香仔仔", 111, "green"));
        list.sort(Comparator.comparing(Apple::getWeight));
        list.forEach(l -> System.out.println(l));
    }
    /**
     * 内部类与方法引用
     */
    private static void test2() {
        // 内部类
        File path = new File(new File("."), "tests");//获取当前目录下的tests文件
        File[] files = path.listFiles(new FileFilter() {//找出tests文件下所有隐藏的文件
            @Override
            public boolean accept(File pathname) {
                return !pathname.isHidden();
            }
        });
        for (File file : files) {
            System.out.println(file.getName());
        }
        // 方法引用
        File path_2 = new File(new File("."), "tests");
        File[] files_2 = path_2.listFiles(File::isHidden);
        for (File file : files_2) {
            System.out.println(file.getName());
        }
    }
    /**
     * 筛选出绿苹果
     */
    private static List<Apple> test3() {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple("臭狗砸", 222, "red"));
        list.add(new Apple("香仔仔", 111, "green"));
        List<Apple> greenApples = new ArrayList<>();
        for (Apple apple : list) {
            if ("green".equals(apple.getColor())) {
                greenApples.add(apple);
            }
        }
        greenApples.stream().forEach(System.out::println);
        return greenApples;
    }
    /**
     * 重量超过150g的苹果
     */
    private static List<Apple> test4() {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple("臭狗砸", 222, "red"));
        list.add(new Apple("香仔仔", 111, "green"));
        List<Apple> weightApples = new ArrayList<>();
        for (Apple apple : list) {
            if (apple.getWeight() > 150) {
                weightApples.add(apple);
            }
        }
        weightApples.stream().forEach(System.out::println);
        return weightApples;
    }
    /**
     * 筛选出绿苹果_方法引用
     */
    private static List<Apple> test3_1(Predicate<Apple> p) {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple("臭狗砸", 222, "red"));
        list.add(new Apple("香仔仔", 111, "green"));
        List<Apple> greenApples = new ArrayList<>();
        for (Apple apple : list) {
            if (p.test(apple)) {
                greenApples.add(apple);
            }
        }
        greenApples.stream().forEach(System.out::println);
        return greenApples;
    }
    /**
     * 重量超过150g的苹果_方法引用
     */
    private static List<Apple> test4_1(Predicate<Apple> p) {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple("臭狗砸", 222, "red"));
        list.add(new Apple("香仔仔", 111, "green"));
        List<Apple> weightApples = new ArrayList<>();
        for (Apple apple : list) {
            if (p.test(apple)) {
                weightApples.add(apple);
            }
        }
        weightApples.stream().forEach(System.out::println);
        return weightApples;
    }
    /**
     * 遍历map，筛选出大于5000的交易，并根据货币分组
     */
    private static void test5() {
        Currency rmb = new Currency("人民币");
        Currency my = new Currency("美元");
        List<Transaction> transactions = Arrays.asList(
                new Transaction(new BigDecimal("1000"), rmb),
                new Transaction(new BigDecimal("2000"), my),
                new Transaction(new BigDecimal("3000"), rmb),
                new Transaction(new BigDecimal("5000"), my),
                new Transaction(new BigDecimal("6000"), rmb),
                new Transaction(new BigDecimal("7000"), my),
                new Transaction(new BigDecimal("8000"), rmb),
                new Transaction(new BigDecimal("9000"), my));

        Map<Currency, List<Transaction>> map = new HashMap<>();
        for (Transaction transaction : transactions) {
            if (transaction.getPrice().compareTo(new BigDecimal("5000")) > 0) {
                Currency currency = transaction.getCurrency();
                List<Transaction> transactions1 = map.get(currency);
                if (null == transactions1) {
                    transactions1 = new ArrayList<>();
                    map.put(currency, transactions1);
                }
                transactions1.add(transaction);
            }
        }
        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + ":" + m.getValue());
        }
    }
    /**
     * 使用lambda
     */
    private static void test5_1() {
        Currency rmb = new Currency("人民币");
        Currency my = new Currency("美元");
        List<Transaction> transactions = Arrays.asList(
                new Transaction(new BigDecimal("1000"), rmb),
                new Transaction(new BigDecimal("2000"), my),
                new Transaction(new BigDecimal("3000"), rmb),
                new Transaction(new BigDecimal("5000"), my),
                new Transaction(new BigDecimal("6000"), rmb),
                new Transaction(new BigDecimal("7000"), my),
                new Transaction(new BigDecimal("8000"), rmb),
                new Transaction(new BigDecimal("9000"), my));
        Map<Currency, List<Transaction>> map = transactions.stream()
                .filter(t -> t.getPrice().compareTo(new BigDecimal("5000")) > 0)
                .collect(Collectors.groupingBy(Transaction::getCurrency));
        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + ":" + m.getValue());
        }
    }
    /**
     * 筛选出比较重的苹果
     */
    private static void test6() {
        List<Apple> apples = Arrays.asList(
                new Apple("臭狗砸", 222, "red"),
                new Apple("香仔仔", 111, "green"));
        Stopwatch stopwatch = Stopwatch.createStarted();
        // 顺序处理
        apples.stream()
                .filter(a -> a.getWeight() > 150)
                .collect(Collectors.toList())
                .forEach(System.out::println);
        logger.info("顺序处理时间为:{}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        stopwatch.reset();
        stopwatch.start();
        // 并行处理
        apples.parallelStream()
                .filter(a -> a.getWeight() > 150)
                .collect(Collectors.toList())
                .forEach(System.out::println);
        logger.info("并行处理时间为:{}",stopwatch.elapsed(TimeUnit.MILLISECONDS));

    }

}
